package com.mall.user.services;

import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IMemberService;
import com.mall.user.IRegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import com.mall.user.utils.ExceptionProcessorUtils;
import com.mall.user.utils.UUIDUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
@Component
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    JavaMailSender javaMailSender;

    // 发件人邮箱
    @Value("${spring.mail.username}")
    private String myMail;

    // 收件人邮箱
//    @Value("${user-provider.mail.receiveMail}")
    private String receiveMail;

    // 消息主题
    @Value("${user-provider.mail.messageSubject}")
    private String messageSubject;

//    /**
//     *  用户注册
//     *
//     */
//    public UserRegisterResponse addRegisterMember(UserRegisterRequest registerRequest, String uuid){
//        UserRegisterResponse registerResponse = new UserRegisterResponse();
//        try{
//            registerRequest.requestCheck();
//            Member validRegisterMember = new Member();
//            validRegisterMember.setUsername(registerRequest.getUserName());
//            validRegisterMember.setEmail(registerRequest.getEmail());
//            int resultColumn = memberMapper.selectCount(validRegisterMember);
//            if(resultColumn == 1){
//                // 已经注册过了，返回重新注册
//                registerResponse.setCode(SysRetCodeConstants.DATA_REPEATED.getCode());
//                registerResponse.setMsg(SysRetCodeConstants.DATA_REPEATED.getMessage());
//                return registerResponse;
//            }
//
//            // 可以添加注册用户到数据库
//            Date date = new Date();
//            // 向用户表中添加数据
//            // 头像
//            String avatar = "https://s3.ifanr.com/wp-content/uploads/2018/04/avengers-infinity-war-d23-artwork-8k-dl-2048x1152.jpg!720";
//            int resultInsertMember = memberMapper.insert(new Member(null, registerRequest.getUserName(), registerRequest.getUserPwd(),
//                    registerRequest.getEmail(), registerRequest.getEmail(), date, date, null, null, 1, avatar,
//                    null, 0, 0.00, "Y"));
//            // 向用户验证表中插入一条数据
//            int resultInsertUserVerify = userVerifyMapper.insert(new UserVerify(null, registerRequest.getUserName(),
//                    uuid, date, "Y", "N"));
//            if(resultInsertMember == 0 || resultInsertUserVerify == 0){
//                // 插入数据失败，返回
//                registerResponse.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
//                registerResponse.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
//                return registerResponse;
//            }
//            registerResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
//            registerResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
//
//        }catch (Exception e){
//            log.error("MemberServiceImpl.addRegisterMember Occur Exception:" + e);
//            registerResponse.setCode(SysRetCodeConstants.DB_EXCEPTION.getCode());
//            registerResponse.setMsg(SysRetCodeConstants.DB_EXCEPTION.getMessage());
//            ExceptionProcessorUtils.wrapperHandlerException(registerResponse,e);
//        }
//        return registerResponse;
//    }

    /**
     *  用户注册参考,仍需努力呀
     *
     */
    public UserRegisterResponse register(UserRegisterRequest registerRequest){
        UserRegisterResponse registerResponse = new UserRegisterResponse();
        // 判空验证
        registerRequest.requestCheck();
        // 验证用户名是否重复
        validUserNameRepeat(registerRequest);
        // 1.向用户表中插入一条记录
        Member member = new Member();
        member.setUsername(registerRequest.getUserName());
        member.setEmail(registerRequest.getEmail());
        // password要加密处理
        String password = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes());
        member.setPassword(password);
        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setIsVerified("N");
        member.setState(1); // 初始状态

        int effectRow = memberMapper.insert(member);
        if(effectRow != 1){
            // 用户表中数据插入失败
            registerResponse.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            registerResponse.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return registerResponse;
        }

        // 2. 向用户验证表中插入一条记录
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(registerRequest.getUserName());
        // 随机生成的一个uuid
        String key = member.getUsername() + member.getPassword() + UUID.randomUUID().toString();
        String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
        userVerify.setUuid(uuid);
        userVerify.setRegisterDate(new Date());
        userVerify.setIsExpire("N");  // 未过期
        userVerify.setIsVerify("N");  // 未验证
        int row = userVerifyMapper.insert(userVerify);
        if(row != 1){
            log.error("添加数据到用户验证表失败");
            registerResponse.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
            registerResponse.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
            return registerResponse;
        }
        // 3. 发送用户激活邮件
        // 发送用户激活邮件 激活邮件应该是一个链接，
        // 有一个接口去处理我们的用户
        // 参数中的uid是uuid
        // 给收件人邮箱赋值
        receiveMail = registerRequest.getEmail();
        sendEmail(uuid,registerRequest);

        // 打印日志
        log.info("---用户注册成功---");
        registerResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        registerResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return  registerResponse;
    }

    /**
     *  发送用户激活邮件
     *
     * @param uuid
     * @param registerRequest
     */
    private void sendEmail(String uuid, UserRegisterRequest registerRequest) {
        // 创建发送邮件的子类对象
        MySendMailRunnable sendMailRunnable = new MySendMailRunnable(uuid,registerRequest);
        // 创建Thread对象，并且把实现了Runnable接口的子类对象作为参数传递
        Thread thread = new Thread(sendMailRunnable);
        // start方法启动线程
        thread.start();
    }

    /**
     *  使用多线程发送邮件
     *
     */
    // 定义一个类实现Runable接口
    @AllArgsConstructor
    class MySendMailRunnable implements Runnable{
        String uuid;
        UserRegisterRequest registerRequest;
        @Override
        public void run() {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(myMail);
            mailMessage.setTo(receiveMail);
            mailMessage.setSubject(messageSubject);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("http://localhost:9999/user/verify?uid=")
                    .append(uuid).append("&username=").append(registerRequest.getUserName());
            // http://localhost:9999/user/verify?uid=xxx&username=xxx
            mailMessage.setText(stringBuilder.toString());
            javaMailSender.send(mailMessage);
        }
    }

    // 验证用户名是否重复
    private void validUserNameRepeat(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",registerRequest.getUserName());
        /** 相当于sql语句 select * from tb_member where username=#{username}*/
        List<Member> memberList = memberMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(memberList)){
            // 数据库中要添加的用户名已存在
            log.error("用户名已存在，请重试");
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(),
                    SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }

}
